package com.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.bean.Supplier;
import com.wms.bean.User;
import com.wms.config.Result;
import com.wms.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("supplier")
@CrossOrigin
public class SupplierController {
    @Autowired
    SupplierService supplierService;
    @GetMapping("list")
    public Result list() {
       List<Supplier> suppliers = supplierService.list();
       return Result.success(suppliers);
    }
    @PostMapping("add")
    public Result add(@RequestBody Supplier supplier) {
        boolean isSaved = supplierService.save(supplier);
        if (isSaved) {
            return Result.success("供应商添加成功", supplier);
        } else {
            return Result.fail(201, "供应商添加失败");
        }
    }
    @PutMapping("update")
    public Result update(@RequestBody Supplier supplier) {
        boolean isUpdated = supplierService.updateById(supplier);
        if (isUpdated) {
            Supplier updatedSupplier = supplierService.getById(supplier.getSid());
            return Result.success("供应商更新成功", updatedSupplier);
        } else {
            return Result.fail(201, "供应商更新失败");
        }
    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        boolean isDeleted = supplierService.removeById(id);
        if (isDeleted) {
            return Result.success("供应商删除成功");
        } else {
            return Result.fail(201, "供应商删除失败");
        }
    }
    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        IPage<Supplier> result;

        if (searchtext == null || searchtext.isEmpty()) {
            result =supplierService.page(page);
        } else {
            QueryWrapper<Supplier> wrapper = new QueryWrapper<Supplier>();
            wrapper.like("sid", searchtext)
                    .or().like("sname", searchtext);

            result = supplierService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }
}
